#include "Neptuner.h"

#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

#include<iostream>

namespace bfs = boost::filesystem;
using namespace std;

void Neptuner_createDirectoryFor(std::string sFilename)
{
	bfs::path xPath(sFilename);
	xPath = bfs::system_complete(xPath);

	bfs::create_directories(xPath.branch_path());
}

int  Neptuner_getLevel(std::string sRelativePath)
{
	int result=0;
	for(size_t i=0; i<sRelativePath.length(); i++)
		if(sRelativePath[i]=='/')
			result++;
	return result;
}

std::string Neptuner_getRelativizer(int nLevel)
{
	std::string sResult = "../";
	for(int i=0;i<nLevel;i++)
		sResult += "../";
	
	return sResult;
}

void Neptuner_copyDirectory(std::string sSourceDir, std::string sTargetDir, bool bRecurse)
{
	bfs::path xSourceDir(sSourceDir);
	xSourceDir=bfs::system_complete(xSourceDir);
	if((!bfs::exists(xSourceDir)) ||
		(!bfs::is_directory(xSourceDir)))
	{
		cerr<<"Could not find source directory: " << xSourceDir <<endl;
		return;
	}

	bfs::path xTargetDir(sTargetDir);
	xTargetDir=bfs::system_complete(sTargetDir);
	bfs::create_directories(xTargetDir);

	bfs::directory_iterator pxLooper(xSourceDir); 
	bfs::directory_iterator pxLoopEnd;
	bfs::path xSourceEntry;
	bfs::path xTargetEntry;

	for(; pxLooper != pxLoopEnd; ++pxLooper)
	{
		xSourceEntry = *pxLooper;
		xTargetEntry = bfs::complete(bfs::path(xSourceEntry.leaf()), xTargetDir);
		
		try {
		bool bIsDirectory = bfs::is_directory(xSourceEntry);
		if(bIsDirectory)
		{
			if(bRecurse)
			{
				//TODO: Support recursive copy
			}
		}
		else
			//For files
		{
			bfs::create_directories(xTargetEntry.branch_path());

			if(bfs::exists(xTargetEntry))	{
				bfs::remove(xTargetEntry);
			}
			bfs::copy_file(xSourceEntry, xTargetEntry);
		}

		} catch(const std::exception & ex) {
			std::cerr<<pxLooper->leaf() <<": " <<ex.what() <<std::endl;
		}
	}  //End of for()




}